import logging
import os
from datetime import datetime


class LoggerUtils:
    def __init__(self, logger_name=None):
        self.logger = logging.getLogger(logger_name if logger_name else __name__)
        self.logger.setLevel(logging.INFO)

        # 创建日志目录
        logs_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../logs')
        if not os.path.exists(logs_dir):
            os.makedirs(logs_dir)

        # 创建文件处理器
        log_file = os.path.join(logs_dir, f'{datetime.now().strftime("%Y%m%d")}.log')
        file_handler = logging.FileHandler(log_file, encoding='utf-8')
        file_handler.setLevel(logging.INFO)

        # 创建控制台处理器
        console_handler = logging.StreamHandler()
        console_handler.setLevel(logging.INFO)

        # 创建格式化器
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        file_handler.setFormatter(formatter)
        console_handler.setFormatter(formatter)

        # 添加处理器
        self.logger.addHandler(file_handler)
        self.logger.addHandler(console_handler)

    def get_logger(self):
        return self.logger


logger = LoggerUtils().get_logger()
